﻿//Eggtimer by Thomas Arvidsson, 2011-12-27

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

using System.Windows.Threading;
using Microsoft.Phone.Shell;
using Microsoft.Devices;
using Microsoft.Devices.Sensors;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using System.Windows.Resources;

using EggTimer.Altitude;
using EggTimer.StaticUtilityMethods;
using EggTimer.EggClass;

namespace EggTimer
{

    public partial class MainPage : PhoneApplicationPage
    {        
        #region Fields and Properties

        private DispatcherTimer dt = new DispatcherTimer();
        private SoundEffect alarm;
        private Egg egg;
        private AltitudeManager altMan;

        private bool isCounting = false;
        public bool IsCounting 
        {
            get { return isCounting; }
            set 
            { 
                isCounting = value;
                if(IsCounting)
                {
                    SetRadioBtns(false);
                }
                else if (!IsCounting)
                {
                    SetRadioBtns(true);
                }
            } 
        }                    

        #endregion Fields

        /// <summary>
        /// Enable/disable control components with the bool parameter
        /// </summary>
        /// <param name="enable"></param>
        private void SetRadioBtns(bool enable)
        {
            rdoBtnFirmEgg.IsEnabled = enable;
            rdoBtnMediumEgg.IsEnabled = enable;
            rdoBtnSoftEgg.IsEnabled = enable;
            rdoBtnXtraFirmEgg.IsEnabled = enable;

            rdoBtnXtraLarge.IsEnabled = enable;
            rdoBtnLarge.IsEnabled = enable;
            rdoBtnMedium.IsEnabled = enable;
            rdoBtnSmall.IsEnabled = enable;

            rdoFridge.IsEnabled = enable;
            rdoRoom.IsEnabled = enable;

            sliderAltitude.IsEnabled = enable;
        }
        
        /// <summary>
        /// Constructor
        /// </summary>
        public MainPage()
        {
            InitializeComponent();            

            // Set the data context of the listbox control to the sample data
            DataContext = App.ViewModel;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);

            dt.Tick += dt_Tick;
            dt.Interval = TimeSpan.FromSeconds(1);//Set the time between ticks to 1 sec
                        
            altMan = new AltitudeManager();
            egg = new Egg();

            InitializeCheckboxes();

            altMan.AllowGps = false;

            //imgGps.Visibility = System.Windows.Visibility.Collapsed;
            btnGps.Visibility = System.Windows.Visibility.Collapsed;

            txtBlockAltitudeBtn.Visibility = System.Windows.Visibility.Collapsed;

            //Set Idlemode on just in case
            PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Enabled;
            //PhoneApplicationService.Current.ApplicationIdleDetectionMode = IdleDetectionMode.Enabled;
        }

        //protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        //{
        //    MediaLibrary library = new MediaLibrary();

        //    if (NavigationContext.QueryString.ContainsKey(_playSongKey))
        //    {
        //        string playingSong = NavigationContext.QueryString[_playSongKey];

        //        foreach (Song song in library.Songs)
        //        {
        //            if(0 == String.Compare(playingSong, song.Name))
        //            {
        //                _playingSong = song;
        //                break;
        //            }
        //        }
        //        _historyItemLaunch = true;

        //    }
        //    else if (MediaPlayer.State == MediaState.Playing)
        //    {
        //        _playingSong = MediaPlayer.Queue.ActiveSong;
        //        txtBlockSong.Text = _playingSong.Name;
        //        //MediaPlayer.Play(_playingSong);
        //        _historyItemLaunch = true;

        //    }


        //    base.OnNavigatedTo(e);
        //}

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
                        
        }

        
        /// <summary>
        /// Initializes a starting state of the components
        /// </summary>
        private void InitializeCheckboxes()
        {
            rdoBtnXtraLarge.IsChecked = false;
            rdoBtnLarge.IsChecked = false;
            rdoBtnMedium.IsChecked = true;
            rdoBtnSmall.IsChecked = false;

            rdoFridge.IsChecked = true;
            rdoRoom.IsChecked = false;

            rdoBtnSoftEgg.IsChecked = false;
            rdoBtnMediumEgg.IsChecked = true;
            rdoBtnFirmEgg.IsChecked = false;
            rdoBtnXtraFirmEgg.IsChecked = false;

            egg.EggSizeToCount = Egg._eggSizeMedium;
            egg.EggTempBeforeCooking = Egg._eggInFridge;
            egg.EggTempDone = Egg._eggTempMedium;
            
            egg.SecToBoil = egg.GetTimerSeconds();

            IsCounting = false;
            
            txtBlockTimer.FontSize = 20;
            txtBlockTimer.Text = "Add eggs in boiling\nwater and tap Start";
            //txtBlockTimer.Text = secToBoil.ToString();

            sliderAltitude.Value = 200.0;            
        }       
        

        // Load data for the ViewModel Items
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();                                
            }
        }
               

        private void btnStart_Tap(object sender, GestureEventArgs e)
        {
            if (egg.SecToBoil > 0)
            {
                try
                {
                    if (!IsCounting)
                    {
                        VibrateController.Default.Start(new TimeSpan(0, 0, 0, 0, 500));
                    }
                    IsCounting = true;

                    dt.Start();

                    //Turn off idlemode, only during countdown. Both on user and application.            
                    PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
                    PhoneApplicationService.Current.ApplicationIdleDetectionMode = IdleDetectionMode.Disabled;//Makes app running when manually locking screen                 
                }
                catch (Exception ex)
                {
                    PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Enabled;                    
                    MessageBox.Show("Unknown error\nTry to resolve problem by \nrestarting the app\n" + ex.Message);
                }                
            }
            else
            {
                //Do nothing
            }            
        }

        private void btnPause_Tap(object sender, GestureEventArgs e)
        {
            if (dt.IsEnabled)
            {
                dt.Stop();
            }
            //Turn idlemode back on            
            PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Enabled;            
        }

        private void btnReset_Tap(object sender, GestureEventArgs e)
        {
            IsCounting = false;
            if (dt.IsEnabled)
            {
                dt.Stop();
            }
            //Resets the checkboxes
            InitializeCheckboxes();            

            //Turn idlemode back on
            PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Enabled;            
        }  

        /// <summary>
        /// Decrease the counter of seconds every Tick of a second, update the textblock with text
        /// and play sound when counter reaches zero
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dt_Tick(object sender, EventArgs e)
        {
            egg.SecToBoil--;
            txtBlockTimer.FontSize = 48;
            
            //txtBlockTimer.Text = StaticMethods.GetTimerValue((decimal)egg.SecToBoil);
            txtBlockTimer.Text = egg.GetTimerValue();
            
            if (egg.SecToBoil == 0 && dt.IsEnabled)
            {
                VibrateController.Default.Start(new TimeSpan(0, 0, 3));
                PlayAlarmSound();
                dt.Stop();
                
                //Turn idlemode back on
                PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Enabled;                
            }
        }

        /// <summary>
        /// Creates a soundeffect from the xna-framework. Using a Streamresourceinfo to get the location of the file
        /// </summary>
        private void PlayAlarmSound()
        {
            StreamResourceInfo info = Application.GetResourceStream(new Uri("Audio/sfx_alarm_ringing_1.wav", UriKind.RelativeOrAbsolute));

            alarm = SoundEffect.FromStream(info.Stream);
            FrameworkDispatcher.Update();
            alarm.Play();
        }

        /// <summary>
        /// Shows a message about adding eggs.
        /// </summary>
        private void ShowMessInTextbox()
        {            
            txtBlockTimer.FontSize = 20;
            txtBlockTimer.Text = "Add eggs in boiling\nwater and tap Start";
        }


        //private void SetSecondsToBoilEgg()
        //{
        //    //egg.SecToBoil = StaticMethods.GetTimerSeconds(egg.EggSizeToCount, egg.BoilingWaterTemp, egg.EggTempBeforeCooking, egg.EggTempDone);
        //}


        // ////////////////////////////////////////////////////////////////////////////////////////////////////////
        // Size of eggs
        private void rdoBtnSmall_Tap(object sender, GestureEventArgs e)
        {           
            egg.EggSizeToCount = Egg._eggSizeSmall;
            //SetSecondsToBoilEgg();
            egg.SecToBoil = egg.GetTimerSeconds();
            ShowMessInTextbox();         
        }
        private void rdoBtnMedium_Tap(object sender, GestureEventArgs e)
        {             
            egg.EggSizeToCount = Egg._eggSizeMedium;
            //SetSecondsToBoilEgg();
            egg.SecToBoil = egg.GetTimerSeconds();

            ShowMessInTextbox();           
        }
        private void rdoBtnLarge_Tap(object sender, GestureEventArgs e)
        {
            egg.EggSizeToCount = Egg._eggSizeLarge;
            //SetSecondsToBoilEgg();
            egg.SecToBoil = egg.GetTimerSeconds();

            ShowMessInTextbox();           
        }
        private void rdoBtnXtraLarge_Tap(object sender, GestureEventArgs e)
        {
            egg.EggSizeToCount = Egg._eggSizeXL;
            //SetSecondsToBoilEgg();
            egg.SecToBoil = egg.GetTimerSeconds();

            ShowMessInTextbox();   
        }      


        //Temp of eggs before cooking
        private void rdoRoom_Tap(object sender, GestureEventArgs e)
        {           
            egg.EggTempBeforeCooking = Egg._eggInRoom;
            //SetSecondsToBoilEgg();
            egg.SecToBoil = egg.GetTimerSeconds();
           
            ShowMessInTextbox();
        }
        private void rdoFridge_Tap(object sender, GestureEventArgs e)
        {            
            egg.EggTempBeforeCooking = Egg._eggInFridge;
            //SetSecondsToBoilEgg();
            egg.SecToBoil = egg.GetTimerSeconds();
            
            ShowMessInTextbox();
        }


        ///Temp of eggs after cooking
        private void rdoBtnSoftEgg_Tap(object sender, GestureEventArgs e)
        {
            egg.EggTempDone = Egg._eggTempSoft;
            //SetSecondsToBoilEgg();
            egg.SecToBoil = egg.GetTimerSeconds();
            
            ShowMessInTextbox();
        }
        private void rdoBtnMediumEgg_Tap(object sender, GestureEventArgs e)
        {
            egg.EggTempDone = Egg._eggTempMedium;
            //SetSecondsToBoilEgg();
            egg.SecToBoil = egg.GetTimerSeconds();
            
            ShowMessInTextbox();
        }
        private void rdoBtnFirmEgg_Tap(object sender, GestureEventArgs e)
        {
            egg.EggTempDone = Egg._eggTempFirm;
            //SetSecondsToBoilEgg();
            egg.SecToBoil = egg.GetTimerSeconds();
            
            ShowMessInTextbox();            
        }
        private void rdoBtnXtraFirmEgg_Tap_1(object sender, GestureEventArgs e)
        {
            egg.EggTempDone = Egg._eggTempExtraFirm;
            //SetSecondsToBoilEgg();
            egg.SecToBoil = egg.GetTimerSeconds();

            ShowMessInTextbox();
        }
                

        private void sliderAltitude_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (sliderAltitude != null)
            {                
                egg.BoilingWaterTemp = StaticMethods.GetBoilingWaterTemperatureCelcius(sliderAltitude.Value);
                txtBlockAltitudeValue.Text = Math.Round(sliderAltitude.Value, 0) + " feet";
                //SetSecondsToBoilEgg();
                egg.SecToBoil = egg.GetTimerSeconds();
            }
        }


        private void btnGps_Tap(object sender, GestureEventArgs e)
        {
            try
            {
                if (altMan.AllowGps)
                {
                    double altitude;
                    
                    VibrateController.Default.Start(new TimeSpan(0, 0, 0, 0, 40));

                    if (altMan.GpsIsReady)
                    {
                        altitude = (double)Math.Round((decimal)StaticMethods.ConvertFeetFromMeters(altMan.Altitude), 1);

                        //  MessageBox.Show("GPS is ready: " + altitude.ToString() + " feet");

                        sliderAltitude.Value = altitude;
                    }
                    else if (!altMan.GpsIsReady)
                    {
                        MessageBox.Show("Gps is not ready. Check if Location is enabled in the System settings");
                    }
                }
                else if (!altMan.AllowGps)
                    MessageBox.Show("Please enable GPS on startscreen");

            }
            catch (Exception ex)
            {
                MessageBox.Show("Unknown Error. Is your GPS enabled in settings?\n" + ex.Message);
            }
        }
                

        private void chBoxAllowGps_Checked(object sender, RoutedEventArgs e)
        {            
            MessageBoxResult mbr = MessageBox.Show("GPS is used only to collect your altitude. No other data is collected, nor any data is saved permanently. Select cancel to abort GPS being activated.\n\n" +
                                                    "It may take 15-30 seconds until the phone recieves any GPS-signal. Please have patience, or select altitude manually. If you are inside any building, "+ 
                                                        "the GPS-readings may be incorrect. Stand close to a window to get the best result.", "Allow GPS?", MessageBoxButton.OKCancel);
            if (mbr == MessageBoxResult.OK)
            {
                altMan.AllowGps = true;

                btnGps.Visibility = System.Windows.Visibility.Visible;
                txtBlockAltitudeBtn.Visibility = System.Windows.Visibility.Visible;
            }
            else if (mbr == MessageBoxResult.Cancel)
            {
                chBoxAllowGps.IsChecked = false;
            }
        }

        private void chBoxAllowGps_Unchecked(object sender, RoutedEventArgs e)
        {
            altMan.AllowGps = false;
            
            btnGps.Visibility = System.Windows.Visibility.Collapsed;
            txtBlockAltitudeBtn.Visibility = System.Windows.Visibility.Collapsed;
        } 
              
    }
}